using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using CMS.api.Entity;
using CMS.api.Model;
using CMS.api.Repository;
using CMS.api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace CMS.api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class ArticlesController : ControllerBase
    {
        /// <summary>
        /// 用户数据库增删改查的属性
        /// </summary>
        // 用户表
        private ICURDable<Users> _UsersRepository;
        // 文章表
        private ICURDable<Articles> _ArticlesRepository;
        // 文章分类表
        private ICURDable<Article_Category> _Article_CategoryRepository;
        // 文章评论表
        private ICURDable<Article_Comment> _Article_CommentRepository;
        // 文章内容表
        private ICURDable<Article_Content> _Article_ContentRepository;
        // 文章图片表
        private ICURDable<Article_Picture> _Article_PictureRepository;
        // 文章点赞表
        private ICURDable<Article_Like> _Article_LikeRepository;
        // 文章点反对表
        private ICURDable<Article_Low> _Article_LowRepository;
        // 文章浏览记录表
        private ICURDable<Article_View> _Article_ViewRepository;
        // 用于保存token的配置信息
        private TokenParameter _tokenParameter;
        // 用于读取配置文件的信息
        private readonly IConfiguration _configuration;

        public ArticlesController(
            IConfiguration configuration,
            ICURDable<Articles> ArticlesRepository,
            ICURDable<Article_Category> Article_CategoryRepository,
            ICURDable<Article_Comment> Article_CommentRepository,
            ICURDable<Article_Content> Article_ContentRepository,
            ICURDable<Article_Picture> Article_PictureRepository,
            ICURDable<Article_Like> Article_LikeRepository,
            ICURDable<Article_Low> Article_LowRepository,
            ICURDable<Article_View> Article_ViewRepository,
            ICURDable<Users> UsersRepository
        )
        {
            _ArticlesRepository = ArticlesRepository;
            _Article_CategoryRepository = Article_CategoryRepository;
            _Article_CommentRepository = Article_CommentRepository;
            _Article_ContentRepository = Article_ContentRepository;
            _Article_PictureRepository = Article_PictureRepository;
            _Article_LikeRepository = Article_LikeRepository;
            _Article_LowRepository = Article_LowRepository;
            _Article_ViewRepository = Article_ViewRepository;
            _UsersRepository = UsersRepository;

            _configuration = configuration;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }




        /// <summary>
        /// 根据文章Id删除文章
        /// </summary>
        /// <param name="id">需要传入:ArticleId</param>
        /// <returns></returns>
        [HttpDelete, Route("deleteArticle/{id}")]
        public dynamic DeleteArticleById(int id)
        {
            var article = _ArticlesRepository.Table.Where(x => x.Id == id).FirstOrDefault();
            article.IsDeleted = true;
            var tmp = new
            {
                Code = 200,
                Data = article,
                Msg = "删除文章成功"
            };
            return JsonHelper.Serialize(tmp);
        }



        // 查询文章类型名称
        [HttpGet, Route("ArticleCategory")]
        public dynamic GetArticleCategory()
        {
            var articleCategory = _Article_CategoryRepository.Table.ToList();
            var tmp = new
            {
                Code = 200,
                Data = articleCategory,
                Msg = "分类名称"
            };
            return JsonHelper.Serialize(tmp);
        }

        // 查询文章信息
        [HttpGet]
        public dynamic Get()
        {
            // 查询文章表所有内容
            var aritcles = _ArticlesRepository.Table.Where(x => x.IsDeleted == false).ToList();
            var aritcleContent = _Article_ContentRepository.Table.ToList();
            var aritcleComment = _Article_CommentRepository.Table.ToList();
            var articleCategory = _Article_CategoryRepository.Table.ToList();
            var aritclePicture = _Article_PictureRepository.Table.ToList();
            var aritcleView = _Article_ViewRepository.Table.ToList();
            var aritcleLike = _Article_LikeRepository.Table.ToList();
            var aritcleLow = _Article_LowRepository.Table.ToList();
            var user = _UsersRepository.Table.ToList();

            var a = aritcles.Select(o =>
            {
                var con = aritcleContent.Where(x => x.ArticleId == o.Id).FirstOrDefault();
                var com = aritcleComment.Where(x => x.ArticleId == o.Id && x.IsDeleted == false).Select(y => y.ArticleCommentContent);
                var categoryname = articleCategory.Where(x => x.Id == o.ArticleCategoryId).Select(y => y.CategoryName).FirstOrDefault();
                var comcount = aritcleComment.Where(x => x.ArticleId == o.Id && x.IsDeleted == false).Count();
                var pic = aritclePicture.Where(x => x.ArticleId == o.Id).Select(y => y.ArticlePictureUrl).FirstOrDefault();
                var likecount = aritcleLike.Where(x => x.ArticleId == o.Id).Count();
                var lowcount = aritcleLow.Where(x => x.ArticleId == o.Id).Count();
                var viewcount = aritcleView.Where(x => x.ArticleId == o.Id && x.IsBrowse.Equals(true)).Count();
                var username = user.Where(x => x.Id == o.UserId).Select(y => y.Username).FirstOrDefault();


                return new AritcleModel
                {
                    ArticleId = o.Id,
                    // 作者名称
                    UserName = username,
                    // 文章图片
                    ArticlePictureUrl = pic,
                    // 文章简介
                    ArticleIntro = o.ArticleIntro,
                    // 文章标题
                    ArticleTitle = o.ArticleTitle,
                    // 文章内容
                    ArticleContent = con.ArticleContent, 
                    //  HttpUtility.HtmlDecode()
                    // 文章评论
                    ArticleCommentContent = com,
                    // 文章评论数
                    ArticleCommentCount = comcount,
                    // 文章分类名称
                    ArticleCategoryName = categoryname,
                    // 点赞数
                    ArticleLikeCount = likecount,
                    // 点反对数
                    ArticleLowCount = lowcount,
                    // 浏览次数
                    ArticleViewCount = viewcount,
                    // 用户Id
                    UserId = o.Id,
                    // 创建时间 
                    CreateTime = o.CreatedTime
                };

            });

            var tmp = new
            {
                Code = 200,
                Data = a,
                Msg = "试试看能不能查询到想要的数据"
            };


            return JsonHelper.Serialize(tmp);
        }



        /// <summary>
        /// 添加文章信息
        /// </summary>
        /// <param name="aritcle">需要传入:UserId,ArticleCategoryId,ArticleIntro,ArticleTitle,Articlecontent</param>
        /// <returns></returns>
        /// 
        [HttpPost, Route("addAritcle")]
        public dynamic InsterArticles(NewAritcle aritcle)
        {

            // 查找文章分类Id
            var category = _Article_CategoryRepository.Table.Where(x => x.CategoryName == aritcle.ArticleCategory).FirstOrDefault();
            // 查找用户Id
            var u = _UsersRepository.Table.Where(x => x.Username == aritcle.ArticleAuthor).FirstOrDefault();

            // 为空说明无法没有找到文章分类
            if (category == null)
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "添加文章失败,请选择文章的分类"
                };

                return JsonHelper.Serialize(tmp);
            }
            // 用户不存在
            else if (u == null)
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "添加文章失败,请登录后在添加文章"
                };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                var a = new Articles
                {
                    UserId = u.Id,
                    ArticleCategoryId = category.Id,
                    ArticleIntro = aritcle.ArticleIntro,
                    ArticleTitle = aritcle.ArticleTitle
                };
                _ArticlesRepository.Inster(a);

                // 获取刚插入的文章Id
                var articleId = a.Id;

                var c = new Article_Content
                {
                    ArticleId = articleId,
                    ArticleContent = aritcle.ArticleContent
                    // HttpUtility.HtmlEncode()
                };
                _Article_ContentRepository.Inster(c);

                // 查找文章的评论
                var com = _Article_CommentRepository.Table.Where(x => x.ArticleId == articleId).Select(y => y.ArticleCommentContent).ToList();
                // 查找评论数量
                var comcount = com.Count();
                // 查找点赞数量
                var likecount = _Article_LikeRepository.Table.Where(x => x.ArticleId == articleId).Count();
                // 踩一下数量
                var lowcount = _Article_LowRepository.Table.Where(x => x.ArticleId == articleId).Count();
                // 查看浏览次数
                var viewcount = _Article_ViewRepository.Table.Where(x => x.ArticleId == articleId).Count();

                // var p = _Article_PictureRepository.Table.Where(x => x.ArticleId == articleId).FirstOrDefault();

                var tmp = new
                {
                    Code = 200,
                    Data = new AritcleModel
                    {
                        ArticleId = a.Id,
                        // 作者名称
                        UserName = u.Username,
                        // 文章图片
                        // ArticlePictureUrl = p.ArticlePictureUrl,
                        // 文章简介
                        ArticleIntro = a.ArticleIntro,
                        // 文章标题
                        ArticleTitle = a.ArticleTitle,
                        // 文章内容
                        ArticleContent = c.ArticleContent,
                        // HttpUtility.HtmlDecode();
                        // 文章评论
                        ArticleCommentContent = com,
                        // 文章评论数
                        ArticleCommentCount = comcount,
                        // 文章分类名称
                        ArticleCategoryName = category.CategoryName,
                        // 点赞数
                        ArticleLikeCount = likecount,
                        // 点反对数
                        ArticleLowCount = lowcount,
                        // 浏览次数
                        ArticleViewCount = viewcount,
                        // 用户Id
                        UserId = u.Id,
                        // 创建时间
                        CreateTime = a.CreatedTime
                    },
                    Msg = "添加文章成功"
                };

                return JsonHelper.Serialize(tmp);

            }



        }





        /// <summary>
        /// 根据文章Id插入文章图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("InsterArticlePicture/{id}")]
        public dynamic InsterArticlePicture(int id, NewPicture picture)
        {
            // 当前文章图片信息
            var p = _Article_PictureRepository.Table.Where(x => x.ArticleId == id).FirstOrDefault();


            // 如果为空不让他插入图片
            if (picture.ArticlePictureUrl == "")
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "无法插入空的图片"
                };
                return JsonHelper.Serialize(tmp);
            }
            else
            {
                // 如果数据库中不为空说明是修改图片
                if (p != null)
                {


                    p.ArticlePictureUrl = picture.ArticlePictureUrl;
                    p.UpdatedTime = DateTime.Now;
                    var article = getArticleMsg(id);

                    var tmp = new
                    {
                        Code = 200,
                        Data = article,
                        Msg = "修改图片成功"
                    };

                    return JsonHelper.Serialize(tmp);
                }
                // 为空说明是新添加图片
                else
                {
                    var pic = new Article_Picture
                    {
                        ArticleId = id,
                        ArticlePictureUrl = picture.ArticlePictureUrl
                    };

                    _Article_PictureRepository.Inster(pic);

                    var article = getArticleMsg(id);

                    var tmp = new
                    {
                        code = 200,
                        Data = article,
                        Msg = "添加图片成功"
                    };

                    return JsonHelper.Serialize(tmp);
                }

            }




        }

        // 获取当前文章的信息的方法
        public dynamic getArticleMsg(int id)
        {

            // 当前文章的图片信息
            var picture = _Article_PictureRepository.Table.Where(x => x.ArticleId == id).FirstOrDefault();
            // 查找当前文章的文章
            var article = _ArticlesRepository.Table.Where(x => x.Id == id).FirstOrDefault();
            // 当前文章的内容 
            var content = _Article_ContentRepository.Table.Where(x => x.ArticleId == id).FirstOrDefault();
            // 当前文章的评论
            var comment = _Article_CommentRepository.Table.Where(x => x.ArticleId == id && x.IsDeleted == false).Select(y => y.ArticleCommentContent); ;
            // 当前文章的评论数
            var commentCount = _Article_CommentRepository.Table.Where(x => x.ArticleId == id && x.IsDeleted == false).Count();
            // 当前文章的点赞数
            var likeCount = _Article_LikeRepository.Table.Where(x => x.ArticleId == id).Where(y => y.IsDeleted == false).Count();
            // 当前文章的踩一下数
            var lowCount = _Article_LowRepository.Table.Where(x => x.ArticleId == id).Count();
            // 当前文章的浏览次数
            var viewCount = _Article_ViewRepository.Table.Where(x => x.ArticleId == id).Count();
            // 查找当前文章的分类名称
            var category = _Article_CategoryRepository.Table.Where(x => x.Id == article.ArticleCategoryId).FirstOrDefault();

            var tmp = new AritcleModel
            {
                ArticleId = article.Id,
                ArticlePictureUrl = picture.ArticlePictureUrl,
                ArticleCategoryName = category.CategoryName,
                ArticleCommentContent = comment,
                ArticleCommentCount = commentCount,
                ArticleIntro = article.ArticleIntro,
                ArticleTitle = article.ArticleTitle,
                ArticleLowCount = lowCount,
                ArticleViewCount = viewCount,
                ArticleLikeCount = likeCount,
                UserId = article.UserId,
                CreateTime = article.CreatedTime,
                ArticleContent = content.ArticleContent
            };

            return tmp;
        }


        /// <summary>
        /// 添加文章分类
        /// </summary>
        /// <param name="category">需要传入:CategoryName</param>
        /// <returns></returns>
        [HttpPost, Route("InsterCategory")]
        public dynamic InsteArticleCategoryr(NewCategory category)
        {
            var c = new Article_Category
            {
                CategoryName = category.CategoryName
            };
            _Article_CategoryRepository.Inster(c);

            var tmp = new
            {
                Code = 200,
                Data = c,
                Msg = "添加分类成功"
            };

            return JsonHelper.Serialize(tmp);

        }


        /// <summary>
        /// 根据文章Id修改文章信息
        /// </summary>
        /// <param name="id">需要传入:文章Id</param>
        /// <param name="aritcle">需要传入:ArticleContent,ArticleCategory,ArticleTitle.ArticleIntro</param>
        /// <returns></returns>
        [HttpPut, Route("putArticle/{id}")]
        public dynamic putArticle(int id, NewAritcle aritcle)
        {
            // 初始化值
            var articleTitle = aritcle.ArticleTitle;
            var articleCategory = _Article_CategoryRepository.Table.Where(x => x.CategoryName == aritcle.ArticleCategory).FirstOrDefault();
            var articleIntro = aritcle.ArticleIntro;
            var articleContent = aritcle.ArticleContent;

            // 根据文章id查找要修改的文章
            var a = _ArticlesRepository.Table.Where(x => x.Id == id).FirstOrDefault();
            // 根据文章Id查找当前要修改的文章内容
            var con = _Article_ContentRepository.Table.Where(x => x.ArticleId == id).FirstOrDefault();
            // 查找作者
            var u = _UsersRepository.Table.Where(x => x.Id == a.UserId).FirstOrDefault();
            // 根据文章Id查找文章的图片
            var pic = _Article_PictureRepository.Table.Where(x => x.ArticleId == id).Select(y => y.ArticlePictureUrl).FirstOrDefault();
            // 查找文章的评论
            var com = _Article_CommentRepository.Table.Where(x => x.ArticleId == id).Select(y => y.ArticleCommentContent).ToList();
            // 查找评论数量
            var comcount = com.Count();
            // 查找点赞数量
            var likecount = _Article_LikeRepository.Table.Where(x => x.ArticleId == id).Count();
            // 踩一下数量
            var lowcount = _Article_LowRepository.Table.Where(x => x.ArticleId == id).Count();
            // 查看浏览次数
            var viewcount = _Article_ViewRepository.Table.Where(x => x.ArticleId == id).Count();


            a.ArticleTitle = articleTitle;
            a.ArticleCategoryId = articleCategory.Id;
            a.ArticleIntro = articleIntro;
            con.ArticleContent = articleContent;
            a.UpdatedTime = DateTime.Now;
            con.UpdatedTime = DateTime.Now;
            articleCategory.UpdatedTime = DateTime.Now;

            var ar = new AritcleModel
            {
                ArticleId = a.Id,
                UserName = u.Username,
                ArticleCategoryName = articleCategory.CategoryName,
                ArticleContent = con.ArticleContent,
                ArticleTitle = a.ArticleTitle,
                ArticleIntro = a.ArticleIntro,
                ArticleLikeCount = likecount,
                ArticleCommentCount = comcount,
                ArticleCommentContent = com,
                ArticleLowCount = lowcount,
                ArticleViewCount = viewcount,
                ArticlePictureUrl = pic
            };



            var tmp = new
            {
                Code = 200,
                Data = ar,
                Msg = "修改成功"
            };
            return JsonHelper.Serialize(tmp);
        }


    }

}